import random


def generate_random_data(num_objects, num_attributes, density):
    data = []
    data.append("{},{}".format(num_objects, num_attributes))

    for _ in range(num_objects):
        # 计算当前行中1的数量
        num_ones_per_row = int(density * num_attributes)

        # 初始化一行全为0
        row = [0] * num_attributes

        # 随机选择 num_ones_per_row 个位置，将其置为1
        ones_indices = random.sample(range(num_attributes), num_ones_per_row)
        for index in ones_indices:
            row[index] = 1

        data.append(",".join(map(str, row)))

    return "\n".join(data)


def calculate_density_from_relation(num_objects, num_attributes, relation_data):
    num_ones = 0

    for row in relation_data.splitlines()[1:]:  # 忽略第一行（对象数和属性数）
        elements = row.split(",")
        num_ones += elements.count("1")

    total_possible_relations = num_objects * num_attributes
    density = num_ones / total_possible_relations if total_possible_relations > 0 else 0
    return density


def write_data_to_file(file_path, data):
    with open(file_path, 'w') as file:
        file.write(data)


# 设置初始参数
initial_objects = 100
max_objects = 900
increment = 100
num_attributes = 100  # 假设属性数固定为100
density = 0.04  # 4%

# 从初始对象数到最大对象数，以增量生成数据并计算密度
current_objects = initial_objects
while current_objects <= max_objects:
    random_data = generate_random_data(current_objects, num_attributes, density)

    # 根据对象数和属性数生成文件名
    file_name = '{}-{}.txt'.format(current_objects, num_attributes)
    file_path = file_name

    # 将数据写入生成的文件
    write_data_to_file(file_path, random_data)

    # 计算密度
    density_calculated = calculate_density_from_relation(current_objects, num_attributes, random_data)
    # print("Objects: {}, Density: {:.4f}".format(current_objects, density_calculated))

    # 增加对象数
    current_objects += increment
